#include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static int  callback(void *data,int columns,char**rows,char **columnNames){
  printf("%s\n",(char*)data);
  for(int i=0;i<columns;i++){
    //输出列名和对应的值
    printf("%d列名:%s=列值%s\n",i,columnNames[i],rows[i]);
  }
   printf("end\n");
  return 0;
}


int query_prod_list(char *sql,char ***result,int* rows,int* cols){
  sqlite3 *db;
  char *errMsg;
  int res = sqlite3_open("mydb.db",&db);
  if(res){
    fprintf(stderr,"查询商品列表信息，打开数据库有误:%s\n",sqlite3_errmsg(db));
    return -1;
  }
  //sql = sqlite3_mprintf ("select * from product");
  res = sqlite3_get_table (db, sql,result , rows, cols,&errMsg);
  printf("sql=%s\n",sql);
  if(res!=SQLITE_OK){
    printf("查询商品列表信息出现错误：%s\n",errMsg);
    sqlite3_free(errMsg);
  }
  int index = *cols;
  printf("cols=%d\n",*cols);
  printf("rows=%d\n",*rows);
  for(int i=0;i<*rows;i++){
    for(int j=0;j<*cols;j++){
      printf("index=%d\n",index);
      printf("列名：%s,列值:%s\n",(*result)[j],(*result)[index]);
      index++;
    }
    printf("\n");

  }

   //关闭数据库
  sqlite3_close(db);
  return 0;
}
/*修改商品*/
int prod_update(char *sql){
  sqlite3 *db;
  char *errMsg;
  int res = sqlite3_open("mydb.db",&db);
  if(res){
    fprintf(stderr,"修改商品信息，打开数据库有误:%s\n",sqlite3_errmsg(db));
    return -1;
  }
  //sql = sqlite3_mprintf ("select * from product");
  res = sqlite3_exec (db, sql,callback,NULL,&errMsg);
  printf("sql=%s\n",sql);
  if(res!=SQLITE_OK){
    printf("修改商品信息出现错误：%s\n",errMsg);
    sqlite3_free(errMsg);
    return -2;
  }
 //关闭数据库
  sqlite3_close(db);
  return 0;
}

/*修改商品*/
int prod_add(char *sql){
  sqlite3 *db;
  char *errMsg;
  int res = sqlite3_open("mydb.db",&db);
  if(res){
    fprintf(stderr,"新增商品信息，打开数据库有误:%s\n",sqlite3_errmsg(db));
    return -1;
  }
  //sql = sqlite3_mprintf ("select * from product");
  res = sqlite3_exec (db, sql,callback,NULL,&errMsg);
  printf("sql=%s\n",sql);
  if(res!=SQLITE_OK){
    printf("新增商品信息出现错误：%s\n",errMsg);
    sqlite3_free(errMsg);
    return -2;
  }
 //关闭数据库
  sqlite3_close(db);
  return 0;
}

/*修改商品*/
int prod_delete(char *sql){
  sqlite3 *db;
  char *errMsg;
  int res = sqlite3_open("mydb.db",&db);
  if(res){
    fprintf(stderr,"删除商品信息，打开数据库有误:%s\n",sqlite3_errmsg(db));
    return -1;
  }
  //sql = sqlite3_mprintf ("select * from product");
  res = sqlite3_exec (db, sql,callback,NULL,&errMsg);
  printf("sql=%s\n",sql);
  if(res!=SQLITE_OK){
    printf("删除商品信息出现错误：%s\n",errMsg);
    sqlite3_free(errMsg);
    return -2;
  }
 //关闭数据库
  sqlite3_close(db);
  return 0;
}

/* int main(){ */
/*   char **result; */
/*   int rows; */
/*   int cols; */
/*   query_prod_list ("select * from product",&result,&rows,&cols); */

/*   sqlite3_free_table(result); */
/*   return 0; */
/* } */
